- Add Two Numbers
Published:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
时间复杂度O(n),空间复杂度O(n)解法,n为max(l1,l2)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null) return null;
ListNode head = new ListNode(0);
ListNode cur = head;
int carry = 0;
while(l1 != null && l2 != null) {
int and = l1.val + l2.val + carry;
carry = and/10;
cur.next = new ListNode(and%10);
cur = cur.next;
l1 = l1.next;
l2 = l2.next;
}
while(l1 != null) {
int and = l1.val + carry;
carry = and/10;
cur.next = new ListNode(and%10);
cur = cur.next;
l1 = l1.next;
}
while(l2 != null) {
int and = l2.val + carry;
carry = and/10;
cur.next = new ListNode(and%10);
cur = cur.next;
l2 = l2.next;
}
if(carry != 0) {
cur.next = new ListNode(carry);
}
return head.next;
}
}
时间复杂度O(n),空间复杂度O(1)解法,n为max(l1,l2)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null) return null;
ListNode cur1 = l1;
ListNode cur2 = l2;
int carry = 0;
ListNode pre = null;
while(cur1 != null && cur2 != null) {
int and = cur1.val + cur2.val + carry;
cur1.val = and%10;
carry = and/10;
pre = cur1;
cur1 = cur1.next;
cur2 = cur2.next;
}
if(cur1 == null) pre.next = cur2;
cur1 = pre.next;
while(cur1 != null) {
int and = cur1.val + carry;
cur1.val = and%10;
carry = and/10;
pre = cur1;
cur1 = cur1.next;
}
if(carry != 0) {
pre.next = new ListNode(carry);
}
return l1;
}
}